<template>
    <div class="jianzhan-content">
        <crumb name="销售统计"></crumb>
        <div style="text-align: left;padding-left: 40px;display: inline-block">
            <span style="display:inline-block">年份</span>
            <el-date-picker v-model="year"
                            type="year"
                            class="picker"
                            value-format="yyyy"
                            size="small"
                            placeholder="year"></el-date-picker>
        </div>
        <div style="text-align: left;padding-left: 40px;display: inline-block">
            <span style="display:inline-block">类型</span>
            <el-select v-model="model"
                       style="margin-left: 10px;"
                       placeholder="类型"
                       size="small">
                <el-option
                        v-for="item in [{id:1,text:'月'},{id:2,text:'季'}]"
                        :key="item.id"
                        :label="item.text"
                        :value="item.id">
                </el-option>
            </el-select>
        </div>
        <div class="echarts-content" style="width: 100%;">
            <bar-chart :options="options"
                       style="margin-top: 10px;
                                width: 50%;
                                 display: inline-block;
                                 vertical-align: top;
                                 text-align: left"> </bar-chart>
            <el-table
                    :data="this.model === 1 ? tableData1 : tableData"
                    border
                    style="width: 50%;display: inline-block;vertical-align: top;margin-top: 10px;">
                <el-table-column
                        prop="date"
                        label="日期"
                >
                </el-table-column>

                <el-table-column
                        prop="price"
                        label="金额">
                    <template slot-scope="scope">
                        <span>{{scope.row.price | toMoney}}</span>
                    </template>
                </el-table-column>
            </el-table>
            <bar-chart :options="options3"> </bar-chart>
            <bar-chart :options="options4"> </bar-chart>
        </div>

        <div class="echarts-content" style="width: 100%;">
            <bar-chart :options="options2"
                       style="margin-top: 10px;
                                width: 100%;
                                 display: block;
                                 vertical-align: top;
                                 text-align: left"> </bar-chart>
        </div>
    </div>
</template>


<script>
    import moment from 'moment'
    import crumb from '../../components/common/crumb'
    import barChart from '../../components/shanxi/barChart'
    import {getChartSaleData, getLineChart, getUseRatePieChart} from "../../api/shanxi";
    import {ERROR_OK} from "../../util/config";
    import {money} from "../../util";

    function getTwoDayBefore(day) {
        const date = new Date(day);
        let days = [];
        const dateSeconds = 86400000;
        for (let i = 1; i <= 3; i++) {
            const newDay = new Date(date.getTime() - (i * dateSeconds));
            // const year = newDay.getFullYear();
            const month = newDay.getMonth() + 1;
            const day = newDay.getDate();
            days.unshift(month + '-' + day)
        }
        return days;
    }

    function getTwoDayLater(day) {
        const date = new Date(day);
        let days = [];
        const dateSeconds = 86400000;
        for (let i = 1; i <= 3; i++) {
            const newDay = new Date(date.getTime() + (i * dateSeconds));
            // const year = newDay.getFullYear();
            const month = newDay.getMonth() + 1;
            const day = newDay.getDate();
            days.push(month + '-' + day)
        }
        return days;
    }

    function combineDay(day) {
        const newDay = new Date(day);
        // const year = newDay.getFullYear();
        const month = newDay.getMonth() + 1;
        const d = newDay.getDate();
        return [...getTwoDayBefore(day), `${month}-${d}`, ...getTwoDayLater(day)]
    }

    export default {
        name: "sale-chart",
        data() {
            const year = new Date().getFullYear().toString();
            let month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map(item => item + "月");
            let season = [1, 2, 3, 4].map(item => item + "季");
            return {
                day: moment().format('YYYY'),
                year: year,
                season: season,
                legend: ['销售金额'],
                customerPriceList: [],
                model: 1,
                data: [],
                data1: [],
                data2: [],
                data3: [],
                data4: [],
                data5: [],
                tableData: [],
                tableData1: [],
                month,
                days3: [],
                userRateX:[]
            }
        },
        created() {
            this.getLineData();
            this.getChartSaleData();
            this.getUseRate();
        },
        computed: {
            // options5() {
            //     return {
            //         color: ['#003366', '#006699', '#4cabce', '#e5323e'],
            //         legend: {
            //             data: ['Total Value', 'Box Number', 'Total Number']
            //         },
            //         title: {
            //             text: 'Ship' + ' Data',
            //             left: 10
            //         },
            //         toolbox: {
            //             feature: {
            //                 dataZoom: {
            //                     yAxisIndex: false
            //                 },
            //                 saveAsImage: {
            //                     pixelRatio: 2
            //                 }
            //             }
            //         },
            //         tooltip: {
            //             trigger: 'axis',
            //             axisPointer: {
            //                 type: 'shadow'
            //             }
            //         },
            //         grid: {
            //             bottom: 90
            //         },
            //         dataZoom: [{
            //             type: 'inside'
            //         }, {
            //             type: 'slider'
            //         }],
            //         xAxis: {
            //             data: this.data5.map(item => item.shipInformation),
            //             silent: false,
            //             splitLine: {
            //                 show: false
            //             },
            //             splitArea: {
            //                 show: false
            //             }
            //         },
            //         yAxis: [
            //             {
            //                 type: 'value',
            //                 name: '金额',
            //                 axisLabel: {
            //                     formatter: '{value} IDR'
            //                 }
            //             },
            //             {
            //                 type: 'value',
            //                 name: '数量',
            //                 axisLabel: {
            //                     formatter: '{value} '
            //                 }
            //             }
            //         ],
            //         series: [
            //             {
            //                 type: 'bar',
            //                 name: 'Total Value',
            //                 data: this.data5.map(item => item.totalAmount),
            //                 // Set `large` for large data amount
            //             },
            //             {
            //                 type: 'bar',
            //                 name: 'Box Number',
            //                 yAxisIndex: 1,
            //                 data: this.data5.map(item => item.boxNumber),
            //                 large: true
            //                 // Set `large` for large data amount
            //             },
            //             {
            //                 type: 'bar',
            //                 name: 'Total Number',
            //                 yAxisIndex: 1,
            //                 data: this.data5.map(item => item.totalNumber),
            //                 // Set `large` for large data amount
            //             },
            //         ]
            //     };
            // },
            options4() {
                return {
                    toolbox: {
                        show: true,
                        feature: {
                            saveAsImage: {
                                show: true,
                                title: 'Save As Image'
                            },
                            dataView: {
                                show: true,
                                title: 'Data View'
                            },
                        },
                    },
                    title: {
                        text: '销售配件年度使用比例',
                        subtext: '陕汽集团',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        data: this.userRateX,
                    },
                    color:['pink','green','orange','white','#ccc','#abcdef','#f3f3f3'],
                    label: {
                        show: true,
                        formatter: "{b} : {c} ({d}%)"
                    },
                    series: [
                        {
                            name: '金额',
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: this.data4,
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(255, 255, 255, 0.5)',
                                }

                            }
                        }
                    ]
                }
            },
            options3() {
                return {
                    toolbox: {
                        show: true,
                        feature: {
                            saveAsImage: {
                                show: true,
                                title: 'Save As Image'
                            },
                            dataView: {
                                show: true,
                                title: 'Data View'
                            },
                        },
                    },
                    title: {
                        text: '销售配件年度进销存比例',
                        subtext: '陕汽集团',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        data: ['出库配件总金额', '在库配件总金额', '备货配件总金额', '发运配件总金额']
                    },
                    label: {
                        show: true,
                        formatter: "{b} : {c} ({d}%)"
                    },
                    series: [
                        {
                            name: '金额',
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: this.data3,
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)',
                                }

                            }
                        }
                    ]
                }

            },
            options() {
                return {
                    toolbox: {
                        show: true,
                        feature: {
                            saveAsImage: {
                                show: true,
                                title: 'Save As Image'
                            },
                            dataView: {
                                show: true,
                                title: 'Data View'
                            },
                        },
                    },
                    dataZoom: [{
                        type: 'inside'
                    }, {
                        type: 'slider'
                    }],
                    title: {
                        show: true,
                        textAlign: "left ",
                        text: '陕汽销售数据',
                    },
                    bar: {
                        center: ['50%', '54%']
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'right',
                        data: this.legend,
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: this.model === 1 ? this.month : this.season,
                            nameTextStyle:{
                                color:'#ccc'
                            },
                            axisLabel:{
                                color:'#ccc'
                            },
                            axisTick: {
                                alignWithLabel: true
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            name: '销售金额(人民币-元)',
                            nameTextStyle:{
                                color:'#ccc'
                            },
                            axisLabel:{
                                color:'#ccc'
                            }
                        }
                    ],
                    series: [
                        {
                            name: '销售金额',
                            type: 'bar',
                            data: this.model === 1 ? this.data : this.data1,
                        }
                    ].concat(
                        this.customerPriceList.map(item => {
                            return {
                                name: item.label,
                                label: {
                                    show: true,
                                    formatter: '{a}: {c}'
                                },
                                type: 'bar',
                                data: this.model === 1 ? item.price : item.monthPrice
                            }
                        })
                    )
                }
            },
            options2() {
                return {
                    toolbox: {
                        show: true,
                        feature: {
                            saveAsImage: {
                                show: true,
                                title: 'Save As Image'
                            },
                            dataView: {
                                show: true,
                                title: 'Data View'
                            },
                        },
                    },
                    color:['#ccc'],
                    title: {
                        text: '在库金额'
                    },
                    dataZoom: [{
                        type: 'inside'
                    }, {
                        type: 'slider'
                    }],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'line'        // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: this.days3,
                        nameTextStyle:{
                            color:'#ccc'
                        },
                        axisLabel:{
                            color:'#ccc'
                        }
                    },
                    yAxis: {
                        type: 'value',
                        min: 0,
                        nameTextStyle:{
                            color:'#ccc'
                        },
                        axisLabel:{
                            color:'#ccc'
                        }
                    },
                    series: [{
                        data: this.data2,
                        smooth: true,
                        type: 'line'
                    }]
                }
            }
        },
        filters: {
            toMoney(m) {
                return money(m)
            }
        },
        methods: {
            async getLineData() {
                const {status, data} = await getLineChart({warehouse:1});
                if (status === ERROR_OK) {
                    this.days3 = data.map(item => item.recordDate)
                    this.data2 =  data.map(item => item.inventoryPrice)
                }
            },
            async getUseRate() {
                const {status, data} = await getUseRatePieChart();
                if (status === ERROR_OK) {
                    this.userRateX = Object.keys(data)
                    this.data4 = this.userRateX.map(item=>{
                        return {
                            value:data[item],
                            name:item
                        }
                    });
                }
            },
            async getChartSaleData() {
                function isNullArray(arr) {
                    return arr.some(item => {
                        return parseFloat(item) > 0
                    })
                }

                const {status, data} = await getChartSaleData({
                    year:this.year,
                    warehouse: 1,
                    belongModule: 1
                });
                let p = [];
                let price = 0;
                if (status === ERROR_OK) {
                    this.data3 = [
                        {value: data.sum_price.sum_stock_out_price, name: '出库配件总金额'},
                        {value: data.sum_price.sum_stock_price, name: '在库配件总金额'},
                        {value: data.sum_price.sum_ready_price, name: '备货配件总金额'},
                        {value: data.sum_price.sum_send_price, name: '发运配件总金额'},
                    ];
                    Object.keys(data.customer_price).forEach(item => {
                        this.customerPriceList.push({
                            label: item,
                            price: Object.keys(data.customer_price[item]).map(m => data.customer_price[item][m]),
                            monthPrice:[]
                        })
                    })
                    this.customerPriceList = this.customerPriceList.filter(item => {
                        return isNullArray(item.price)
                    })
                    this.customerPriceList && this.customerPriceList.forEach(item => {
                        let prices = 0
                        item.price.forEach((p, idx) => {
                            if ((idx + 1) % 3 !== 0) {
                                prices += parseFloat(p)
                            }
                            if ((idx + 1) % 3 === 0) {
                                item.monthPrice.push(prices.toFixed(2))
                                prices = 0;
                            }
                        })
                        this.legend.push(item.label)
                    })

                    Object.keys(data.price).forEach((item, idx) => { // 统计季度价格
                        if ((idx + 1) % 3 !== 0) {
                            price += data.price[item].sumStockOutPrice
                        }
                        if ((idx + 1) % 3 === 0) {
                            p.push(price.toFixed(2));
                            price = 0;
                        }
                    });
                    this.data1 = p;
                    this.tableData = p.map((item, idx) => {
                        return {
                            date: `第${3 * idx + 1}-${3 * idx + 3}月`,
                            price: item
                        }
                    });
                    this.tableData1 = Object.keys(data.price).map((item) => {
                        return {
                            date: `第${item}月`,
                            price: data.price[item].sumStockOutPrice
                        }

                    })
                    this.data = Object.keys(data.price).map((item) => {
                        return data.price[item].sumStockOutPrice
                    })

                }
            }
        }
        ,
        watch: {
            year() {
                this.getChartSaleData()
            }
            ,
            day() {
                this.getLineData()
            }
        }
        ,
        components: {
            crumb,
            barChart
        }
    }
</script>

<style scoped lang="scss">
    .picker {
        display: inline-block;
        margin-top: 10px;
        margin-left: 10px;
    }
</style>